<?php
namespace App\Models\Traits;

use App\Models\Movie;
use App\Models\MovieWatchUser;

trait UserWatching
{

    public function isWatch($movie)
    {
        // 返回用户是否在追(过)某个剧
        return MovieWatchUser::where('user_id', $this->id)->where('movie_id', self::keyId($movie))->first() ? true : false;
    }

    public function isWatching($movie)
    {
        // 返回用户是否正在追某个剧
        return MovieWatchUser::where('user_id', $this->id)->where('movie_id', self::keyId($movie))->where('status', 'watching')->first() ? true : false;
    }

    public function isWatched($movie)
    {
        // 返回用户是否追过某个剧
        return MovieWatchUser::where('user_id', $this->id)->where('movie_id', self::keyId($movie))->where('status', 'watched')->first() ? true : false;
    }

    public function watching($movie)
    {
        // 追某个剧
        $this->updateWatchStatus($movie, 'watching');
        // if ($this->isWatch($movie)) $this->movies()->updateExistingPivot(self::keyId($movie), ['status' => 'watching']);
        // else $this->movies()->attach(self::keyId($movie), ['status' => 'watching']);
    }
    public function watched($movie)
    {
        $this->updateWatchStatus($movie, 'watched');
        // 追过某个剧
        // if ($this->isWatch($movie)) $this->movies()->updateExistingPivot(self::keyId($movie), ['status' => 'watched']);
        // else $this->movies()->attach(self::keyId($movie), ['status' => 'watched']);
    }

    public function unWatch($movie)
    {
        // 取消追
        $this->movies()->detach(self::keyId($movie));
    }
    public function watchings()
    {
        // 返回用户正在追的剧
        return $this->movies()->wherePivot('status', 'watching');
    }

    public function watcheds()
    {
        // 用户追过的剧
        return $this->movies()->wherePivot('status', 'watched');
    }

    public function watchs()
    {
        return $this->movies();
    }
    // 修改状态
    public function updateWatchStatus($movie, $status = 'watched')
    {
        if ($this->isWatch($movie)) $this->movies()->updateExistingPivot(self::keyId($movie), ['status' => $status]);
        else $this->movies()->attach(self::keyId($movie), ['status' => $status]);
    }
    protected static function keyId($movie)
    {
        return !is_a($movie, Movie::class) ? $movie : $movie->id;
    }
}
